package lk.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lk.util.ResponseUtil;
import lk.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * author lk
 *
 * @date 2021/10/27 11:18
 * @description TODO
 * @since 1.0
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityIgnore securityIgnore;


    @Resource(name = "jacksonObjectMapper")
    private ObjectMapper objectMapper;

    /**
     * 加密器
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordUtil.passwordEncoder();
    }


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().access("@authorizeService.check(authentication,request)");
//        http.authorizeRequests().anyRequest().authenticated(); // 所有的请求必须有权限
        http.exceptionHandling().authenticationEntryPoint((request, response, authException) -> {
            ResponseUtil.responseFailed(objectMapper, response, "处理失败");
        }); // 未登陆时访问接口 提示
        http.exceptionHandling().accessDeniedHandler((request, response, accessDeniedException) -> {
            ResponseUtil.responseFailed(objectMapper, response, "没有该权限");
        }); // 没有权限时提示的信息

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(authFilter(), UsernamePasswordAuthenticationFilter.class);
        http.csrf().disable();
        // 防止 csrf攻击
//        http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(securityIgnore.getIgnoreList());
    }

    @Bean
    public AuthFilter authFilter() {
        return new AuthFilter();
    }


}
